package com.tencent.sr.iris.basic.mp.service;

import com.tencent.sr.iris.basic.mp.dependency.CosDependency;
import com.tencent.sr.iris.basic.mp.interfaces.request.GetUploadUrlRequest;
import com.tencent.sr.iris.basic.mp.interfaces.request.GetVisitUrlRequest;
import com.tencent.sr.iris.basic.mp.interfaces.response.GetUploadUrlResponse;
import com.tencent.sr.iris.basic.mp.interfaces.response.GetVisitUrlResponse;
import com.tencent.sr.rmall.common.exception.code.BaseErrorCode;
import com.tencent.sr.rmall.common.exception.retail.TRetailBizException;
import java.net.URL;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CosService {

    @Autowired
    private CosDependency cosDependency;

    public GetUploadUrlResponse getUploadPicUrl(GetUploadUrlRequest request) {
        String objPath = request.getSaasId() + "/" + request.getUid();
        if (request.getSource().compareToIgnoreCase(GetUploadUrlRequest.SOURCE_COMMODITY) == 0) {
            objPath += "/commodity";
        } else {
            throw new TRetailBizException(BaseErrorCode.REQUEST_ERROR, "未知的来源");
        }

        if (request.getMediaType().compareToIgnoreCase(GetUploadUrlRequest.MEDIA_TYPE_PIC) == 0) {
            objPath += "/pic";
        } else if (request.getMediaType().compareToIgnoreCase(GetUploadUrlRequest.MEDIA_TYPE_VIDEO) == 0) {
            objPath += "/video";
        } else {
            throw new TRetailBizException(BaseErrorCode.REQUEST_ERROR, "未知的媒体类型");
        }

        objPath += (new Date()).getTime();
        objPath += "." + request.getFileSuffix();
        URL url = cosDependency.getPreSignedUrl(objPath);
        GetUploadUrlResponse resp = new GetUploadUrlResponse();
        resp.setUploadUrl(url.toString());
        resp.setBucket(cosDependency.getBucket());
        resp.setRegion(cosDependency.getRegion());
        resp.setKey(objPath);
        return resp;
    }

    public GetVisitUrlResponse getVisitUrl(GetVisitUrlRequest request) {

        String[] pathElem = request.getCosKey().split("/");
        if (pathElem.length <= 2) {
            throw new TRetailBizException(BaseErrorCode.REQUEST_ERROR, "参数错误");
        }
        if (pathElem[0].compareToIgnoreCase(request.getSaasId()) != 0
                || pathElem[1].compareToIgnoreCase(request.getUid()) != 0) {
            throw new TRetailBizException(BaseErrorCode.REQUEST_ERROR, "参数错误");
        }

        cosDependency.setPublicRead(request.getCosKey());
        GetVisitUrlResponse resp = new GetVisitUrlResponse();
        resp.setVisitUrl("https://" + cosDependency.getBucket() + ".cos." + cosDependency.getRegion() + ".myqcloud.com/"
                + request.getCosKey());

        return resp;
    }
}
